<?php

namespace App\Common\Libs;

use Illuminate\Support\Str;

class IdBuilder
{

    /**
     * 生成 32 位随机字符串
     * @param int $length
     * @return string
     */
    public static function getRandomStr($length = 32)
    {
        return Str::random($length);
    }

    /**
     * 生成 24 位随机 ID
     * @param string $time
     * @param string $serverNumber
     * @param int $length
     * @return string
     */
    public static function getUniqueID($time = '', $serverNumber = '00', $length = 24)
    {
        try {
            $time = $time ? $time . random_int(100, 500) : self::getMillisecond();
            $time36 = base_convert($time, 10, 36);
            $randStr = Str::random($length - strlen($serverNumber . $time36));
            $randStr = str_replace(['-', '_'], [random_int(0, 9), random_int(0, 9)], $randStr);
            return strtoupper($serverNumber . $time36 . $randStr);
        } catch (\Exception $e) {
            return Str::random(24);
        }
    }

    /**
     * 获取毫秒级时间戳
     * @return float
     */
    protected static function getMillisecond()
    {
        list($microFirst, $microSecond) = explode(' ', microtime());
        return (float)sprintf('%.0f', ((float)$microFirst + (float)$microSecond) * 1000);
    }

}
